package com.aiden.app.common.util;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;
import android.view.WindowManager;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * 调用相机相册剪切工具类
 * Created by yanggeng on 2017/3/23 0023.
 */

public class CameraAndAlbumUtils {

    private static File cameraFile;
    private static Uri mPhotoFileUri;
    public static String SAVED_HEAD_IMAGE_DIR_PATH =
            Environment.getExternalStorageDirectory().getPath() + File.separator + "headImg";
    public static String SAVED_FEEDBACK_IMAGE_DIR_PATH =
            Environment.getExternalStorageDirectory().getPath() + File.separator + "feedbackImg";

    public static int MODE_HEAD = 0x101;
    public static int MODE_FEEDBACK = 0x102;

    /**
     * 打开相机
     *
     * @param context
     * @param cameraPath 文件路径
     * @param filename   文件名（包含后缀）
     * @return 启动相机的intent
     */
    public static Intent openCamera(Activity context, String cameraPath, String filename) {
        if ((ContextCompat.checkSelfPermission(context, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) ||
                (ContextCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)) {
            //如果没有授权，则请求授权
            ActivityCompat.requestPermissions(context, new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
            return null;
        } else {
            int currentApiVersion = Build.VERSION.SDK_INT;
            String imagePath = cameraPath + File.separator + filename;
            cameraFile = new File(cameraPath);
            if (!cameraFile.exists()) {
                cameraFile.mkdirs();
            }
            if (currentApiVersion >= Build.VERSION_CODES.N) {
                mPhotoFileUri = FileProvider.getUriForFile(context, "com.dahu.app.provider", new File(imagePath));//通过FileProvider创建一个content类型的Uri
            } else {
                mPhotoFileUri = Uri.fromFile(new File(imagePath));
            }
            Intent cameraIntent = new Intent(
                    MediaStore.ACTION_IMAGE_CAPTURE);
            cameraIntent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, mPhotoFileUri);
            return cameraIntent;
        }

    }

    /**
     * 打开相册
     * 因为要剪切，所以调用之前要定义图片存放uri
     *
     * @return 打开相册的intent
     */
    public static Intent choosePicture() {
        Intent innerIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        innerIntent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
        Intent wrapperIntent = Intent.createChooser(innerIntent, null);
        return wrapperIntent;
    }

    /**
     * 打开剪切
     *
     * @param inUri  要剪切的图片uri
     * @param outUri 剪切完保存的图片uri
     * @return 打开剪切的intent
     */
    public static Intent openCrop(Uri inUri, Uri outUri, boolean isSquare) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(inUri, "image/*");
        if (inUri.equals(outUri)) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                if (inUri.equals(outUri)) {
                    intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
                }
            }
        }

        // crop为true是设置在开启的intent中设置显示的view可以剪裁
        intent.putExtra("crop", "true");

        if (!isSquare) {
            // 自由裁剪
            intent.putExtra("aspectX", 0.1);
            intent.putExtra("aspectY", 0.1);
        } else {
            // aspectX aspectY 是宽高的比例
            intent.putExtra("aspectX", 1);
            intent.putExtra("aspectY", 1);
            // outputX,outputY 是剪裁图片的宽高
            intent.putExtra("outputX", 600);
            intent.putExtra("outputY", 600);
        }
        intent.putExtra("scale", true); // 自由裁剪
        intent.putExtra("scaleUpIfNeeded", true);
        intent.putExtra("return-data", false);
        intent.putExtra("noFaceDetection", true);
        LogUtils.INSTANCE.e("startPhotoZoom", "打开裁剪功能");
        intent.putExtra(MediaStore.EXTRA_OUTPUT, outUri);
        intent.putExtra("outputFormat", Bitmap.CompressFormat.PNG.toString());
        return intent;
    }

    /**
     * 可设置裁剪宽高比
     *
     * @param inUri
     * @param outUri
     * @param width
     * @param height
     * @return
     */
    public static Intent openCrop(Uri inUri, Uri outUri, int width, int height) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(inUri, "image/*");
        if (inUri.equals(outUri)) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                if (inUri.equals(outUri)) {
                    intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
                }
            }
        }

        // crop为true是设置在开启的intent中设置显示的view可以剪裁
        intent.putExtra("crop", "true");

        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", width);
        intent.putExtra("aspectY", height);
        // outputX,outputY 是剪裁图片的宽高
        intent.putExtra("outputX", 600);
        intent.putExtra("outputY", 600);

        intent.putExtra("scale", true); // 自由裁剪
        intent.putExtra("return-data", false);
        intent.putExtra("noFaceDetection", true);
        LogUtils.INSTANCE.e("startPhotoZoom", "打开裁剪功能");
        intent.putExtra(MediaStore.EXTRA_OUTPUT, outUri);
        intent.putExtra("outputFormat", Bitmap.CompressFormat.PNG.toString());
        return intent;
    }

    /**
     * uri -> bitmap
     *
     * @param context
     * @param uri
     * @return
     */
    public static Bitmap getBitmap(Activity context, Uri uri) {
        File file2 = new File(context.getExternalCacheDir(),
                System.currentTimeMillis() + ".png");

        BufferedOutputStream bos;
        Bitmap bitmap = null;
        try {
            bitmap = MediaStore.Images.Media.getBitmap(context.getContentResolver(), uri);
            bos = new BufferedOutputStream(new FileOutputStream(file2));
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, bos);
            bos.flush();
            bos.close();

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return bitmap;
    }

    public int readPictureDegree(String path) {
        int degree = 0;
        try {
            ExifInterface exifInterface = new ExifInterface(path);
            int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
            switch (orientation) {
                case ExifInterface.ORIENTATION_ROTATE_90:
                    degree = 90;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_180:
                    degree = 180;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_270:
                    degree = 270;
                    break;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return degree;
    }

    public void rotatePhoto(int angle, String cameraPath, Activity context) {

        WindowManager wm = context.getWindowManager();
        int windowWidth = wm.getDefaultDisplay().getWidth();
        int windowHeight = wm.getDefaultDisplay().getHeight();

        BitmapFactory.Options opts = new BitmapFactory.Options();
        opts.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(cameraPath, opts);
        opts.inPreferredConfig = Bitmap.Config.RGB_565;
        int bitmapHeight = opts.outHeight;
        int bitmapWidth = opts.outWidth;
        if (bitmapHeight > windowHeight || bitmapWidth > windowWidth) {
            int scaleX = bitmapWidth / windowWidth;
            int scaleY = bitmapHeight / windowHeight;
            if (scaleX > scaleY)//按照水平方向的比例缩放
                opts.inSampleSize = scaleX;
            else//按照竖直方向的比例缩放
                opts.inSampleSize = scaleY;
        } else {//图片比手机屏幕小 不缩放
            opts.inSampleSize = 1;
        }
        opts.inJustDecodeBounds = false;
        Matrix m = new Matrix();
        m.postRotate(angle);
        Bitmap bitmap = null;
        try {
            bitmap = BitmapFactory.decodeFile(cameraPath, opts);
            if (bitmap == null)
                return;
            bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), m, true);// 重新生成图片
//            saveToFile(bitmap);//将新生成的图片保存到指定位置，以供后面裁剪时调用，具体代码就不贴出了
        } catch (OutOfMemoryError e) {
            System.gc();
        } finally {
            if (bitmap != null)
                bitmap.recycle();
        }
    }

    /**
     * bitmap 转换为file保存到本地目录
     *
     * @param context
     * @param fileName
     * @param bitmap
     * @return
     */
    public static String saveBitmapToFile(Context context, String fileName, Bitmap bitmap) {
        if (null == context || null == bitmap) {
            return null;
        }
        if (TextUtils.isEmpty(fileName)) {
            return null;
        }
        FileOutputStream fOut = null;
        try {
            File file = null;
            String fileDstPath = "";
            if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                // 保存到sd卡
                fileDstPath = Environment.getExternalStorageDirectory().getAbsolutePath()
                        + File.separator + context.getPackageName() + File.separator + "headImage" + File.separator + fileName;

                File homeDir = new File(Environment.getExternalStorageDirectory().getAbsolutePath()
                        + File.separator + context.getPackageName() + File.separator + "headImage" + File.separator);
                if (!homeDir.exists()) {
                    homeDir.mkdirs();
                }
            } else {
                // 保存到file目录
                fileDstPath = context.getFilesDir().getAbsolutePath()
                        + File.separator + context.getPackageName() + File.separator + "headImage" + File.separator + fileName;

                File homeDir = new File(context.getFilesDir().getAbsolutePath()
                        + File.separator + context.getPackageName() + File.separator + "headImage" + File.separator);
                if (!homeDir.exists()) {
                    homeDir.mkdir();
                }
            }

            file = new File(fileDstPath);

            if (!file.exists()) {
                // 简单起见，先删除老文件，不管它是否存在。
                file.delete();

                fOut = new FileOutputStream(file);
                if (fileName.endsWith(".jpg")) {
                    bitmap.compress(Bitmap.CompressFormat.JPEG, 75, fOut);
                } else {
                    bitmap.compress(Bitmap.CompressFormat.PNG, 100, fOut);
                }
                fOut.flush();
                bitmap.recycle();
            }

            LogUtils.INSTANCE.d("FileSave", "saveDrawableToFile " + fileName
                    + " success, save path is " + fileDstPath);
            return fileDstPath;
        } catch (Exception e) {
            LogUtils.INSTANCE.e("FileSave", "saveDrawableToFile: " + fileName + " , error:" + e);
            return null;
        } finally {
            if (null != fOut) {
                try {
                    fOut.close();
                } catch (Exception e) {
                    LogUtils.INSTANCE.e("FileSave", "saveDrawableToFile, close error:" + e);
                }
            }
        }
    }

    public static String getSavedFeedbackImageDirPath() {
        return SAVED_FEEDBACK_IMAGE_DIR_PATH;
    }

    public static Uri getUri(Context context, File file) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            return FileProvider.getUriForFile(context, "com.dahu.app.provider", file);
        } else {
            return Uri.fromFile(file);
        }
    }

    public static String getPath(Context context, Uri uri) {
        if ("content".equalsIgnoreCase(uri.getScheme())) {
            if (isGooglePhotosUri(uri)) {
                return uri.getLastPathSegment();
            }
            return getDataColumn(context, uri, null, null);
        } else {
            return uri.toString();
        }
    }

    public static String getDataColumn(Context context, Uri uri, String selection,
                                       String[] selectionArgs) {

        Cursor cursor = null;
        final String column = "_data";
        final String[] projection = {
                MediaStore.Images.ImageColumns.DATA
        };

        try {
            cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
                    null);
            if (cursor != null && cursor.moveToFirst()) {
                final int index = cursor.getColumnIndexOrThrow(column);
                return cursor.getString(index);
            }
        } finally {
            if (cursor != null)
                cursor.close();
        }
        return null;
    }

    public static boolean isGooglePhotosUri(Uri uri) {
        return "com.google.android.apps.photos.content".equals(uri.getAuthority());
    }
}
